package ua.com.mind_tree.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.HasKeyboardPagingPolicy;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import ua.com.mind_tree.client.experience.Experience;
import ua.com.mind_tree.client.service.ExperienceService;

import java.util.List;

public class Main implements EntryPoint {
    public static final List<Experience> TEST_DATA = ExperienceService.getTestData();
    public static final ListDataProvider<Experience> provider = new ListDataProvider<Experience>(TEST_DATA);
    private ExpDetailsPanel detailsPanel = new ExpDetailsPanel();


    public void onModuleLoad() {
        CellList<Experience> cellList = prepareCellList();
        PageManager.getInstance().setMenu(cellList);
        PageManager.getInstance().setContent(detailsPanel);
    }

    private CellList<Experience> prepareCellList() {


        ExpCell textCell = new ExpCell();
        CellList<Experience> cellList = new CellList<Experience>(textCell);
        provider.addDataDisplay(cellList);
        cellList.setKeyboardPagingPolicy(HasKeyboardPagingPolicy.KeyboardPagingPolicy.INCREASE_RANGE);
        cellList.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.BOUND_TO_SELECTION);
        prepareSelectionModel(cellList);
        cellList.setRowCount(TEST_DATA.size(), true);
        cellList.setRowData(0, TEST_DATA);
        return cellList;
    }

    private void prepareSelectionModel(CellList<Experience> cellList) {
        final SingleSelectionModel<Experience> selectionModel = new SingleSelectionModel<Experience>();
        cellList.setSelectionModel(selectionModel);
        selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
            public void onSelectionChange(SelectionChangeEvent event) {
                Experience selected = selectionModel.getSelectedObject();
                if (selected != null) {
                    detailsPanel.update(selected);
                }
            }
        });
    }

}
